<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager;

use app\admin\model\Team;
use app\common\library\Curl;
use app\common\model\Authentication;
use app\common\model\CaptainApplication;
use app\common\model\Level;
use app\common\model\MatchComment;
use app\common\model\RelationImage;
use app\common\model\Store;
use app\common\model\TeamComment;
use app\common\model\User;
use app\common\model\UserTeam;
use think\Db;
use think\Exception;

class CommentManager extends BaseManager
{

    const TYPE_TEAM = 'team';
    const TYPE_MATCH = 'match';
    /**
     * 组队评论
     * @param User $user 用户信息
     * @param array $data 数据
     * @param bool $trans 是否开启事物
     * @return void
     */
    public static function CommentAboutTeam(User $user,array $data,bool $trans=true):array
    {
        if ($trans)
            Db::startTrans();
        try {
            $data['user_id'] = $user->id;
            $teamModel = new TeamComment();
            $image = $data['image'] ?? '';
            unset($data['image']);
            $id = $teamModel->insertGetId($data);
            if (!$id){
                throw new Exception('评论失败');
            }

            /**
             * 处理评论的图片
             */
            if ($image){
                $images = explode(',',$image);
                if (is_array($images) && count($images) > 0){
                    foreach ($images as $v){
                        $imageInsert[] = [
                            'type' => RelationImage::TYPE_TEAM_COMMENT ,
                            'relation_id' => $id,
                            'url' => $v,
                            'create_time' => time(),
                        ];
                    }

                    if ($imageInsert){
                        RelationImage::insertAll($imageInsert);
                    }
                }
            }

            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }


    /**
     * 删除组队评论
     * @param User $user
     * @param int $id
     * @param bool $trans
     * @return array
     */
    public static function delCommentAboutTeam(User $user,int $id,bool $trans=true):array
    {
        if ($trans)
            Db::startTrans();
        try {
            TeamComment::where('tuc_id',$id)->where('user_id',$user->id)->delete();
            RelationImage::where('relation_id',$id)->where('type',RelationImage::TYPE_TEAM_COMMENT)->delete();
            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 获取组队评论列表
     * @param int $id
     * @param int $pid
     * @param int $page
     * @param int $step
     * @return array
     */
    public static function listAboutTeam(int $id,int $user_id=0,int $pid=0,int $page=1,int $step=20):array
    {
        try {
            if (!$id){
                throw new Exception('参数有误');
            }
            $start = ($page-1)*$step;
            $teamCommentModel = new \app\common\model\TeamComment();
            $count = $teamCommentModel
                ->where('t_id',$id)
                ->where(function ($query) use($pid){
                    if ($pid){
                        return $query->where('up_tuc_Id',$pid);
                    }
                })
                ->count();

            $info = $teamCommentModel->alias('utc')
                ->where('utc.t_id',$id)
                ->where(function ($query) use($pid){
                    if ($pid){
                        return $query->where('utc.up_tuc_Id',$pid);
                    }
                })
                ->join('user u','u.id=utc.user_id','inner')
                ->join('user_account ua','ua.user_id=utc.user_id','inner')
                ->join('level l','u.level=l.vl_id','left')
                ->field('utc.tuc_id,utc.user_id,u.avatar,u.nickname,u.gender,u.level,l.vip_name,l.vip_icon,utc.content,utc.ct_date,ua.join_count,ua.team_count,ua.match_count')
                ->limit($start,$step)
                ->select();
            if ($info){
                foreach ($info as &$v){
                    if ($user_id > 0 && $v['user_id'] == $user_id){
                        $v['is_delete'] = 1;
                    }else{
                        $v['is_delete'] = 0;
                    }
                    $image = RelationImage::where('type',RelationImage::TYPE_TEAM_COMMENT)->where('relation_id',$v['tuc_id'])->field('url')->select();
                    $v['image'] = $image;
                    if ($v['vip_icon'] && strrpos($v['vip_icon'],'https') === false){
                        $v['vip_icon'] = cdnurl($v['vip_icon']);
                    }
                }
            }

            $pageData = page($count,$step,$page);
            $return['list'] = $info;
            $data = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($data);
        }catch (Exception $e){
            self::setStatusCode(self::$failCode);
            self::setMessage($e->getMessage());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }


    /**
     * 赛事评论
     * @param User $user 用户信息
     * @param array $data 数据
     * @param bool $trans 是否开启事物
     * @return void
     */
    public static function CommentAboutMatch(User $user,array $data,bool $trans=true):array
    {
        if ($trans)
            Db::startTrans();
        try {
            $data['user_id'] = $user->id;
            $matchCommentModel = new MatchComment();
            $image = $data['image'] ?? '';
            unset($data['image']);
            $id = $matchCommentModel->insertGetId($data);
            if (!$id){
                throw new Exception('评论失败');
            }

            /**
             * 处理评论的图片
             */
            if ($image){
                $images = explode(',',$image);
                if (is_array($images) && count($images) > 0){
                    foreach ($images as $v){
                        $imageInsert[] = [
                            'type' => RelationImage::TYPE_MATCH_COMMENT ,
                            'relation_id' => $id,
                            'url' => $v,
                            'create_time' => time(),
                        ];
                    }

                    if ($imageInsert){
                        RelationImage::insertAll($imageInsert);
                    }
                }
            }

            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }


    /**
     * 删除赛事评论
     * @param User $user
     * @param int $id
     * @param bool $trans
     * @return array
     */
    public static function delCommentAboutMatch(User $user,int $id,bool $trans=true):array
    {
        if ($trans)
            Db::startTrans();
        try {
            if(MatchComment::where('umc_id',$id)->where('user_id',$user->id)->delete()){
                RelationImage::where('relation_id',$id)->where('type',RelationImage::TYPE_MATCH_COMMENT)->delete();
            }
            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 获取赛事评论列表
     * @param int $id
     * @param int $pid
     * @param int $page
     * @param int $step
     * @return array
     */
    public static function listAboutMatch(int $id,int $pid=0,int $page=1,int $step=20):array
    {
        try {
            if (!$id){
                throw new Exception('参数有误');
            }
            $matchCommentModel = new \app\common\model\MatchComment();
            $count = $matchCommentModel
                ->where('m_id',$id)
                ->where(function ($query) use($pid){
                    if ($pid){
                        return $query->where('up_umc_Id',$pid);
                    }
                })
                ->count();

            $info = $matchCommentModel->alias('umc')
                ->where('umc.m_id',$id)
                ->where(function ($query) use($pid){
                    if ($pid){
                        return $query->where('umc.up_umc_Id',$pid);
                    }
                })
                ->join('user u','u.id=umc.user_id','inner')
                ->field('umc.umc_id,u.avatar,u.nickname,u.gender,u.level,umc.content,utc.ct_date')
                ->select();
            if ($info){
                foreach ($info as &$v){
                    $image = RelationImage::where('type',RelationImage::TYPE_MATCH_COMMENT)->where('relation_id',$v['umc_id'])->field('url')->select();
                    $v['image'] = $image;
                }
            }

            $pageData = page($count,$step,$page);
            $return['list'] = $info;
            $data = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($data);
        }catch (Exception $e){
            self::setStatusCode(self::$failCode);
            self::setMessage($e->getMessage());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }

    private static function check($message)
    {
        try {
            $curl = new Curl();
            $curl->setUrl('https://luckycola.com.cn/tools/sensiWords');
        }catch (Exception $e){
            self::setStatusCode(self::$failCode);
            self::setMessage($e->getMessage());
        }
    }

}